import config from '@/config'
import services from '@/services'
import { LoginStatus } from '@/services/auth/'
import { aiChatFailed, type AIChatMaySuccess } from './definition'
import { logger } from './index'

export async function requestAIChat<T>(
  path: string,
  requestParams?: RequestInit & { data?: unknown },
) {
  const auth = services.auth.info$.value
  if (auth.status !== LoginStatus.LoggedIn) return aiChatFailed('尚未登录')
  const { token } = auth.account

  const { data: requestData, ...extraParams } = requestParams ?? {}

  try {
    const headers: Record<string, string> = {
      token,
    }
    let body: string | FormData | undefined
    if (requestData instanceof FormData) {
      body = requestData
    } else if (requestData !== undefined) {
      headers['Content-Type'] = 'application/json; charset=utf-8'
      body = JSON.stringify(requestData)
    }

    const url = join(config.AI_CHAT_API, path)
    const res = await fetch(url, {
      method: 'POST',
      ...extraParams,
      headers,
      body,
    })
    if (res.status === 200) {
      return (await res.json()) as AIChatMaySuccess<T>
    } else {
      return aiChatFailed(await res.text())
    }
  } catch (e) {
    logger.warn('AI Chat 请求失败', e)
    return aiChatFailed('网络连接失败')
  }
}

function join(...nodes: string[]) {
  if (!nodes.length) return ''
  return nodes
    .map((node, index) => {
      if (index > 0 && node.startsWith('/')) node = node.slice(1)
      if (index !== nodes.length - 1 && node.endsWith('/')) node = node.slice(0, -1)
      return node
    })
    .join('/')
}
